﻿#!/usr/bin/env python
#coding:utf-8


import os
import sys
import ctypes
import pymysql
import pymongo
import memcache
import struct
import time

#from pg import DB
import _pg as pg

import ConfigParser as config
import common_tools

# APP前端 解密对象
oi_tea = None		

# 配置文件名
run_type = 1	# 1=dev; 2=test, 3=pre, 4=dist
dev_config_path   = '../config/devl_config.ini'
oper_config_path  = '../config/oper_config.ini'
test_config_path  = '../config/test_config.ini'
pre_config_path  = '../config/pre_config.ini'


# 配置文件解析出来的参数
online_memcache = [];
apns_memcache = [];
group_memcache = [];
location_memcache = [];
im_mysql = {}
postgre_sql = {}
roam_url = {}
mongo_sql = {}
im_data_url = {}

exe_conn_transfor = {}	# 这里配置的是内网地址，公网的脚本不能使用这个配置
exe_conn_im = {}


# 取当前文件的绝对路径
'''
def get_current_path() :
	all_my_file = sys.path[0] + '/' + __file__
	dir_name, file_name = os.path.split(all_my_file)
	return dir_name + '/'
'''

#################################################################################
def initialize(run_env) :
	global online_memcache, apns_memcache, group_memcache, location_memcache;
	global im_mysql, postgre_sql, roam_url, mongo_sql, im_data_url;
	global exe_conn_transfor, exe_conn_im;
	global oi_tea, run_type;

	current_path = common_tools.get_current_path()

	oi_tea = ctypes.CDLL(current_path + "../lib/liboi_tea.so")

	# 根据参数识别配置文件名
	cfg_name = dev_config_path;	run_type = 1
	if run_env == 'test' or run_env == 'tst':
		cfg_name = test_config_path;
		run_type = 2
	elif run_env == 'pre':
		cfg_name = pre_config_path;
		run_type = 3
	elif run_env == 'operation' or run_env == 'dist' or run_env == 'run':
		cfg_name = oper_config_path;
		run_type = 4
#	else:	# 其它情况都是默认，相当于deve开发环境

	cfg_name = current_path + cfg_name;
#	print 'run_env=%s, cfg_name=%s' %(run_env, cfg_name);

	cf = config.ConfigParser()
	cf.read(cfg_name);

	# 读取memcache配置
	online_memcache	= get_one_memcache_config(cf, 'ONLINE');
	apns_memcache		= get_one_memcache_config(cf, 'APNS');
	group_memcache		= get_one_memcache_config(cf, 'GROUP');
	location_memcache	= get_one_memcache_config(cf, 'REAL_LOCATION');

	# 读取数据库配置
	im_mysql = get_one_mysql_config(cf, 'IM_MYSQL_SERVER');
	postgre_sql = get_postgresql_config(cf, 'POSTGRESQL_SERVER');

	roam_c2c	= cf.get('ROAM_GET_URI', 'ROAM_C2C_GET_URI' ); 
	roam_s2c	= cf.get('ROAM_GET_URI', 'ROAM_S2C_GET_URI' ); 
	roam_grp	= cf.get('ROAM_GET_URI', 'ROAM_GROUP_GET_URI' ); 
	roam_url = {'c2c': roam_c2c, 's2c': roam_s2c, 'grp': roam_grp};

	mongo_sql = get_mongosql_config(cf, 'MONGO_SERVER');

	login_url	= cf.get('IM_DATA_URL', 'LOGIN_URL' ); 
	im_data_url = {'login':login_url};

	exe_conn_transfor = get_exe_connect_config(cf, 'TRANSFOR_CONN_ADDR');
	exe_conn_im = get_exe_connect_config(cf, 'IM_CONN_ADDR');
	return cf;


#################################################################################
# 用元组存储memcache的地址列表
def get_one_memcache_config(cf, name) :
	str_section		= 'MEMCACHE_SERVER_' + name;
	str_item_num	= 'MEMCACHE_SERVER_' + name + '_NUM';
	str_item_ip		= 'MEMCACHE_SERVER_' + name + '_IP_';
	str_item_port	= 'MEMCACHE_SERVER_' + name + '_PORT_';
#	print 'str_section   = ', str_section;
#	print 'str_item_num  = ', str_item_num;
#	print 'str_item_ip   = ', str_item_ip;
#	print 'str_item_port = ', str_item_port ;
	number = cf.getint(str_section, str_item_num) ;

	#print 'memcachedb num,%d' % memcachdb_num
	url_array = []
	for ii in range(0, number):
		ip		= cf.get(str_section, str_item_ip + str(ii) );
		port	= cf.get(str_section, str_item_port + str(ii) ); 
		conn_uri = ip + ":" + port		
		url_array.append(conn_uri)
#		print conn_uri;
	return url_array;

#################################################################################
# 用字典存储mysql的配置信息
def get_one_mysql_config(cf, name) :
#	print name;
	str_section		= name;
	host	= cf.get(str_section, 'MYSQL_SERVER_IP_0' );
	port	= cf.get(str_section, 'MYSQL_SERVER_PORT_0' ); 
	user	= cf.get(str_section, 'MYSQL_SERVER_USER_0' );
	passwd	= cf.get(str_section, 'MYSQL_SERVER_PASSWD_0' ); 
	db		= cf.get(str_section, 'MYSQL_SERVER_DB_0' ); 

	dict = {'host': host, 'port': port, 'user': user, 'passwd': passwd, 'db': db};
#	print dict
	return dict

#################################################################################
# 用字典存储mysql的配置信息
def get_postgresql_config(cf, name) :
	str_section		= name;
	host	= cf.get(str_section, 'HOST' );
	port	= cf.get(str_section, 'PORT' ); 
	user	= cf.get(str_section, 'USER' );
	passwd	= cf.get(str_section, 'PASSWD' ); 
	db		= cf.get(str_section, 'DB_NAME' ); 

	dict = {'host': host, 'port': port, 'user': user, 'passwd': passwd, 'db': db};
#	print dict
	return dict


#################################################################################
# 用字典存储mysql的配置信息
def get_mongosql_config(cf, name) :
	str_section		= name;
	uri		= cf.get(str_section, 'URI' ); 
	db		= cf.get(str_section, 'DB_NAME' ); 

	dict = {'uri': uri, 'db': db};
	#print dict
	return dict

#################################################################################
# 用字典存储各个服务的连接信息
def get_exe_connect_config(cf, name) :
	str_section		= name;
	ip		= cf.get(str_section, 'HOST' ); 
	port	= cf.get(str_section, 'PORT' ); 

	dict = {'ip': ip, 'port': port};
	#print dict
	return dict



#################################################################################
#
#	这部分是功能函数，以后可以提出去作为单独的文件
#
#################################################################################


#################################################################################
# 连接mysql数据库，只是为了减少外部调用时的参数书写
def get_im_mysql_conn() :
	KEY_CONNECTED = 'connected'
	if im_mysql.has_key(KEY_CONNECTED) :
		return im_mysql[KEY_CONNECTED]

	db = pymysql.connect(
				host	 = im_mysql['host'], 
				user	 = im_mysql['user'], 
				password = im_mysql['passwd'], 
				db		 = im_mysql['db'], 
				port	 = int(im_mysql['port']), 
				charset  = 'utf8mb4')
	im_mysql[KEY_CONNECTED] = db
	return db

def close_im_mysql_conn() :
	KEY_CONNECTED = 'connected'

	if im_mysql.has_key(KEY_CONNECTED) :
		# 关闭数据库连接
		im_mysql[KEY_CONNECTED].close()
		im_mysql.pop(KEY_CONNECTED)


#################################################################################
# 连接postgresql数据库，只是为了减少外部调用时的参数书写
def get_postgresql_conn() :
#	db = DB(
	db = pg.connect(
				dbname	= postgre_sql['db'], 
				host	= postgre_sql['host'], 
				port	= int(postgre_sql['port']), 
				user	= postgre_sql['user'], 
				passwd	= postgre_sql['passwd'])
	return db


def get_mongo_client() :
	client = pymongo.MongoClient(mongo_sql['uri'])
#	client = pymongo.MongoClient('mongodb://dev_mongo:BUU1dmBRyuKJ8n82vY6R1BpB@dds-bp157b8a4254b1a42.mongodb.rds.aliyuncs.com:3717')
	db = client[mongo_sql['db']]
	return db

def get_mongo_collection(coll_name) :
	client = pymongo.MongoClient(mongo_sql['uri'])
#	client = pymongo.MongoClient('mongodb://dev_mongo:BUU1dmBRyuKJ8n82vY6R1BpB@dds-bp157b8a4254b1a42.mongodb.rds.aliyuncs.com:3717')
	db = client[mongo_sql['db']]
	collection = db[coll_name]  
	return collection




#################################################################################
# 根据手机号码查询用户的uid
def get_uid_with_phonenumber(uid, phonenum) :
	if '0' != uid:
		return str(uid)

	db = get_im_mysql_conn()
	try:
		cursor = db.cursor()
		cursor.execute("SELECT uid FROM table_account_passwd WHERE phone_num = " + phonenum)
		data = cursor.fetchone()
		if None != data :
			uid = data[0]
#		cursor.close()
#		db.close()
	except pymysql.Error,e:
		print '%s ' % str(e)
		return '0'

	return str(uid)

#################################################################################
# 根据手机号码查询用户的uid
def get_uid_with_phonenumber_like(phonenum) :
	uid = '0'

	db = get_im_mysql_conn()
	try:
		cursor = db.cursor()
		cursor.execute("SELECT uid,phone_num FROM table_account_passwd WHERE phone_num LIKE '%%%s%%'" % phonenum)
		data = cursor.fetchone()

		if None != data :
			uid = data[0]
			phonenum = data[1]
#		cursor.close()
#		db.close()
	except pymysql.Error,e:
		print '%s ' % str(e)

	return uid, phonenum

#################################################################################
# 根据手机号码查询用户的uid
def get_phonenumber_with_uid(uid) :
	
	phonenum = ''

	db = get_im_mysql_conn()
	try:
		cursor = db.cursor()
		cursor.execute("SELECT phone_num FROM table_account_passwd WHERE uid = " + uid)
		data = cursor.fetchone()
		if None != data :
			uid = data[0]
#		cursor.close()
#		db.close()
	except pymysql.Error,e:
		print '%s ' % str(e)
		return '0'

	return str(uid)

################################################################################
# 查询用户在线信息
def get_user_online(uid_str, interval=10*60):
	mc = memcache.Client([online_memcache[0]], debug = 0)
	data=mc.get(uid_str)
	if data is None:
		return 0
	uid, nVersion, nStatus, nStatusSeq, nLoginSeq, device_type, sTeaKey, reserved1, nInstanceId, dwLoginTime, dwLastAccessTime, user_ip, already_notified, user_port, sLoginInnerIp, sLoginOuterIp,sLoginPort, cReserved= struct.unpack("=6I17s3s3I17s1sH17s17s6s360s", data)

	if nStatus==10 and (time.time()-dwLastAccessTime) < interval:
		return 1
	else:
		return 0


#################################################################################
def mysql_get_conn() :
	return get_im_mysql_conn();

#执行sql语句并返回结果		
def mysql_execute_result(db, sql):
	if db is None or sql is None:
		return None
	try:
		cursor = db.cursor()
		cursor.execute(sql)
		data = cursor.fetchall()
		return data
	except pymysql.Error,e:
		print '%s ' % str(e)
		cursor.close()		
		return None	



def postgre_execute_result(postgre_db, sql):
	if postgre_db is None or sql is None:
		return []
	try:
		data = postgre_db.query(sql).getresult()
		return data

	except:
		print 'postgre_execute_result ERROR!! sql=[%s]' % sql
		return []


if __name__ == '__main__':
	config = initialize('dev');

	print 'online_memcache	  = ', online_memcache;
	print 'apns_memcache     = ', apns_memcache;
	print 'group_memcache    = ', group_memcache;
	print 'location_memcache = ', location_memcache;

	print 'im_mysql    = ', im_mysql;
	print 'postgre_sql = ', postgre_sql;
	print 'roam_url    = ', roam_url;
	print 'im_url	   = ', im_data_url;


